<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :inline="true" :model="queryParams" class="query-form">
      <el-form-item label="数据集名称" prop="datasetName">
        <el-input
          v-model="queryParams.datasetName"
          placeholder="请输入数据集名称"
          clearable
          size="small"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据集编码" prop="datasetCode">
        <el-input
          v-model="queryParams.datasetCode"
          placeholder="请输入数据集编码"
          clearable
          size="small"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据源" prop="datasourceId">
        <el-select
          v-model="queryParams.datasourceId"
          placeholder="请选择数据源"
          clearable
          size="small"
          style="width: 200px"
        >
          <el-option
            v-for="item in datasourceOptions"
            :key="item.datasourceId"
            :label="item.datasourceName"
            :value="item.datasourceId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数据集类型" prop="datasetType">
        <el-select
          v-model="queryParams.datasetType"
          placeholder="请选择数据集类型"
          clearable
          size="small"
          style="width: 200px"
        >
          <el-option
            v-for="item in datasetTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          size="small"
          style="width: 200px"
        >
          <el-option label="启用" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['system:dataset:add']"
        >
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="small"
          @click="handleDelete"
          :disabled="multiple"
          v-hasPermi="['system:dataset:remove']"
        >
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-refresh-left"
          size="small"
          @click="handleRefresh"
        >
          刷新
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="small"
          @click="handleExport"
          v-hasPermi="['system:dataset:export']"
        >
          导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-s-operation"
          size="small"
          @click="handleBatchRefresh"
        >
          批量刷新
        </el-button>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="datasetList"
      @selection-change="handleSelectionChange"
      border
      fit
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="数据集ID" prop="datasetId" width="80" align="center" />
      <el-table-column
        label="数据集名称"
        prop="datasetName"
        align="center"
        :show-overflow-tooltip="true"
        width="180"
      />
      <el-table-column
        label="数据集编码"
        prop="datasetCode"
        align="center"
        :show-overflow-tooltip="true"
        width="180"
      />
      <el-table-column
        label="数据集类型"
        prop="datasetType"
        align="center"
        width="120"
      >
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.datasetType === 'table'"
            size="small"
            type="primary"
          >
            表
          </el-tag>
          <el-tag
            v-else-if="scope.row.datasetType === 'view'"
            size="small"
            type="success"
          >
            视图
          </el-tag>
          <el-tag
            v-else-if="scope.row.datasetType === 'query'"
            size="small"
            type="warning"
          >
            SQL查询
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="数据源"
        prop="datasourceName"
        align="center"
        :show-overflow-tooltip="true"
        width="180"
      />
      <el-table-column
        label="版本"
        prop="version"
        align="center"
        width="100"
      />
      <el-table-column
        label="数据量"
        prop="dataCount"
        align="center"
        width="100"
      />
      <el-table-column
        label="状态"
        prop="status"
        align="center"
        width="100"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
            active-color="#13ce66"
            inactive-color="#ff4949"
            v-hasPermi="['system:dataset:edit']"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        prop="createTime"
        align="center"
        width="180"
      />
      <el-table-column
        label="元数据"
        align="center"
        width="100"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleMetadataPreview(scope.row)"
            v-hasPermi="['system:dataset:edit']"
          >
            预览
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="结果集"
        align="center"
        width="100"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handlePreviewData(scope.row)"
            v-hasPermi="['system:dataset:edit']"
          >
            预览
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="200"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            type="success"
            size="mini"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
            v-hasPermi="['system:dataset:edit']"
          >
            修改
          </el-button>
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:dataset:remove']"
          >
            删除
          </el-button>
          <el-button
            type="info"
            size="mini"
            icon="el-icon-refresh"
            @click="handleRefreshSingle(scope.row)"
          >
            刷新
          </el-button>
          <el-button
            type="warning"
            size="mini"
            icon="el-icon-menu"
            @click="handleVersion(scope.row)"
            v-hasPermi="['system:dataset:edit']"
          >
            版本
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 数据预览对话框 -->
    <el-dialog
      :title="'数据集预览 - ' + (previewDataset ? previewDataset.datasetName : '')"
      :visible.sync="previewDialogVisible"
      width="90%"
      :before-close="handleClosePreview"
    >
      <div class="preview-container">
        <div class="preview-toolbar">
          <el-form :inline="true" :model="previewParams" class="preview-params-form">
            <el-form-item label="预览行数" prop="limit">
              <el-input
                v-model.number="previewParams.limit"
                placeholder="请输入预览行数"
                size="small"
                style="width: 150px"
                type="number"
                min="1"
                max="1000"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="small" @click="handlePreviewRefresh">
                刷新数据
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table
          v-loading="previewLoading"
          :data="previewDataList"
          border
          fit
          class="preview-table"
        >
          <el-table-column
            v-for="(column, index) in previewColumns"
            :key="index"
            :label="column.name"
            :prop="column.name"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span v-if="typeof scope.row[column.name] === 'object' && scope.row[column.name] !== null">
                {{ JSON.stringify(scope.row[column.name]) }}
              </span>
              <span v-else>{{ scope.row[column.name] }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!previewLoading && previewDataList.length === 0" class="empty-data">
          暂无数据
        </div>
      </div>
    </el-dialog>

    <!-- 批量刷新对话框 -->
    <el-dialog
      title="批量刷新"
      :visible.sync="batchRefreshDialogVisible"
      width="400px"
      :before-close="handleCloseBatchRefresh"
    >
      <div class="batch-refresh-container">
        <div class="refresh-tips">
          <el-alert
            title="提示"
            type="info"
            description="批量刷新会重新加载所选数据集的元数据和数据量信息，可能需要一定时间。"
            show-icon
            :closable="false"
          />
        </div>
        <div class="refresh-progress" v-if="batchRefreshVisible">
          <el-progress
            :percentage="batchRefreshProgress"
            :format="refreshFormat"
          />
          <div class="refresh-status">
            <div>成功: {{ batchRefreshSuccessCount }}</div>
            <div>失败: {{ batchRefreshErrorCount }}</div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCloseBatchRefresh">取消</el-button>
        <el-button type="primary" @click="doBatchRefresh" :disabled="batchRefreshVisible">
          确认刷新
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDatasetList, deleteDataset, updateDataset, getDatasourceList, getDatasetTypeList, refreshDatasets, previewDatasetData, refreshDataset } from "@/api/system/dataset";
import Pagination from "@/components/Pagination";

export default {
  name: "Dataset",
  components: {
    Pagination
  },
  data() {
    return {
      // 表格加载状态
      loading: false,
      // 数据表格数据
      datasetList: [],
      // 数据源选项
      datasourceOptions: [],
      // 数据集类型选项
      datasetTypeOptions: [],
      // 选中数据
      multipleSelection: [],
      // 总数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        datasetName: undefined,
        datasetCode: undefined,
        datasourceId: undefined,
        datasetType: undefined,
        status: undefined
      },
      // 预览对话框
      previewDialogVisible: false,
      // 预览数据集
      previewDataset: null,
      // 预览数据列表
      previewDataList: [],
      // 预览列信息
      previewColumns: [],
      // 预览加载状态
      previewLoading: false,
      // 预览参数
      previewParams: {
        limit: 50
      },
      // 批量刷新对话框
      batchRefreshDialogVisible: false,
      // 批量刷新可见
      batchRefreshVisible: false,
      // 批量刷新进度
      batchRefreshProgress: 0,
      // 批量刷新成功数
      batchRefreshSuccessCount: 0,
      // 批量刷新失败数
      batchRefreshErrorCount: 0
    };
  },
  created() {
    this.getList();
    this.getDatasourceOptions();
    this.getDatasetTypeOptions();
  },
  computed: {
    // 是否选中数据
    multiple() {
      return this.multipleSelection.length === 0;
    }
  },
  methods: {
    // 获取数据集列表
    getList() {
      this.loading = true;
      getDatasetList(this.queryParams)
        .then(response => {
          this.datasetList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 获取数据源选项
    getDatasourceOptions() {
      getDatasourceList().then(response => {
        this.datasourceOptions = response.data;
      });
    },
    // 获取数据集类型选项
    getDatasetTypeOptions() {
      getDatasetTypeList().then(response => {
        this.datasetTypeOptions = response.data;
      });
    },
    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },
    // 处理多选
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
    },
    // 新增
    handleAdd() {
      // 在新页签中打开新增页面
      this.$tab.openPage("新增数据集", "/data/dataset/add");
    },
    // 修改
    handleEdit(row) {
      this.$router.push("/data/dataset/edit/" + row.datasetId);
    },
    // 删除
    handleDelete(row) {
      let ids = row.datasetId ? [row.datasetId] : this.multipleSelection.map(item => item.datasetId);
      this.$modal
        .confirm("确定要删除选中的数据集吗？删除后数据将无法恢复。")
        .then(() => {
          deleteDataset(ids)
            .then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("删除成功");
                this.getList();
                this.multipleSelection = [];
              } else {
                this.$modal.msgError(response.msg);
              }
            })
            .catch(() => {
              this.$modal.msgError("删除失败");
            });
        })
        .catch(() => {});
    },
    // 刷新
    handleRefresh() {
      this.getList();
    },
    // 导出
    handleExport() {
      this.$confirm("确定要导出数据集列表吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          window.open(
            process.env.VUE_APP_BASE_API +
            "/system/dataset/export?" +
            new URLSearchParams(this.queryParams)
          );
        })
        .catch(() => {});
    },
    // 状态变更
    handleStatusChange(row) {
      this.$modal
        .confirm(
          "确定要修改" + row.datasetName + "的状态吗？"
        )
        .then(() => {
          updateDataset(row)
            .then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("修改成功");
              } else {
                this.$modal.msgError(response.msg);
                this.getList(); // 刷新列表以恢复原始状态
              }
            })
            .catch(() => {
              this.$modal.msgError("修改失败");
              this.getList(); // 刷新列表以恢复原始状态
            });
        })
        .catch(() => {
          this.getList(); // 取消操作，刷新列表以恢复原始状态
        });
    },
    // 元数据预览
    handleMetadataPreview(row) {
      // 在新页签中打开元数据预览页面
      this.$tab.openPage("元数据预览 - " + row.datasetName, "/data/dataset/metadata/" + row.datasetId);
    },
    
    // 结果集预览
    handlePreviewData(row) {
      this.previewDataset = row;
      this.previewDialogVisible = true;
      this.previewDataList = [];
      this.previewColumns = [];
      this.handlePreviewRefresh();
    },
    // 刷新预览数据
    handlePreviewRefresh() {
      if (!this.previewDataset) return;

      this.previewLoading = true;
      previewDatasetData(this.previewDataset.datasetId, { limit: this.previewParams.limit })
        .then(response => {
          if (response.code === 200) {
            this.previewDataList = response.data;
            // 动态生成列
            if (this.previewDataList && this.previewDataList.length > 0) {
              this.previewColumns = Object.keys(this.previewDataList[0]).map(key => ({
                name: key
              }));
            } else {
              this.previewColumns = [];
            }
          } else {
            this.$modal.msgError(response.msg);
          }
          this.previewLoading = false;
        })
        .catch(() => {
          this.previewLoading = false;
          this.$modal.msgError("加载预览数据失败");
        });
    },
    // 关闭预览对话框
    handleClosePreview() {
      this.previewDialogVisible = false;
      this.previewDataset = null;
      this.previewDataList = [];
      this.previewColumns = [];
    },
    // 批量刷新
    handleBatchRefresh() {
      if (this.multipleSelection.length === 0) {
        this.$modal.msgWarning("请先选择要刷新的数据集");
        return;
      }
      this.batchRefreshDialogVisible = true;
      this.batchRefreshVisible = false;
      this.batchRefreshProgress = 0;
      this.batchRefreshSuccessCount = 0;
      this.batchRefreshErrorCount = 0;
    },
    // 执行批量刷新
    doBatchRefresh() {
      const ids = this.multipleSelection.map(item => item.datasetId);

      this.batchRefreshVisible = true;
      this.batchRefreshProgress = 0;
      this.batchRefreshSuccessCount = 0;
      this.batchRefreshErrorCount = 0;

      refreshDatasets(ids)
        .then(response => {
          if (response.code === 200) {
            this.batchRefreshProgress = 100;
            this.batchRefreshSuccessCount = response.data.successCount;
            this.batchRefreshErrorCount = response.data.errorCount;

            setTimeout(() => {
              this.batchRefreshDialogVisible = false;
              this.getList(); // 刷新列表
            }, 1000);
          } else {
            this.$modal.msgError(response.msg);
            this.batchRefreshDialogVisible = false;
          }
        })
        .catch(() => {
          this.$modal.msgError("批量刷新失败");
          this.batchRefreshDialogVisible = false;
        });
    },
    // 关闭批量刷新对话框
    handleCloseBatchRefresh() {
      this.batchRefreshDialogVisible = false;
    },
    // 刷新格式化
    refreshFormat(percentage) {
      return `${percentage}%`;
    },
    // 单个刷新
    handleRefreshSingle(row) {
      this.$modal
        .confirm("确定要刷新该数据集的元数据和数据量吗？")
        .then(() => {
          refreshDataset(row.datasetId)
            .then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("刷新成功");
                this.getList();
              } else {
                this.$modal.msgError(response.msg);
              }
            })
            .catch(() => {
              this.$modal.msgError("刷新失败");
            });
        })
        .catch(() => {});
    },
    // 版本管理
    handleVersion(row) {
      this.$router.push("/data/dataset/version-history/" + row.datasetId);
    }
  }
};
</script>

<style scoped>
.query-form {
  margin-bottom: 15px;
}

.mb8 {
  margin-bottom: 8px;
}

.preview-container {
  max-height: 600px;
  overflow: auto;
}

.preview-toolbar {
  margin-bottom: 15px;
}

.preview-table {
  max-height: 500px;
  overflow: auto;
}

.empty-data {
  text-align: center;
  padding: 50px;
  color: #999;
}

.batch-refresh-container {
  padding: 10px 0;
}

.refresh-tips {
  margin-bottom: 20px;
}

.refresh-progress {
  margin-top: 20px;
}

.refresh-status {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  font-size: 14px;
}
</style>
